package org.jbit.news.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jbit.news.biz.NewsBiz;
import org.jbit.news.biz.impl.NewsBizImpl;
import org.jbit.news.entity.News;

public class NewsServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
   		response.setCharacterEncoding("utf-8");
   		String xg=request.getParameter("xg");
   		String nid=request.getParameter("nid");
   		PrintWriter out =response.getWriter();
   		NewsBiz nb=new NewsBizImpl();
   		News news=new News();
		String uploadFileName="";  //待上传的文件名
		String fieldName="";  //表单字段的属性名
		boolean flag=false; 
		boolean isMultipart=ServletFileUpload.isMultipartContent(request);
		//设置上传文件的路径.该方法获取的是upload文件夹在WEB服务其中的绝对路径
		String uploadPath=request.getSession().getServletContext().getRealPath("upload/");
		File file =new File(uploadPath);
		if(!file.exists()){file.mkdirs();}
		if(isMultipart){
			FileItemFactory factory=new DiskFileItemFactory();
			ServletFileUpload upload=new ServletFileUpload(factory);
			List<FileItem> items=null;
			try {
				items = upload.parseRequest(request);
			
			} catch (FileUploadException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			Iterator<FileItem> iter=items.iterator();
			//通过循环处理每个文件
			while(iter.hasNext()){
				FileItem item=iter.next();
				if(item.isFormField()){ //如果是普通表单字段
					fieldName=item.getFieldName();
					if(fieldName.equals("ntid")){
						news.setNtid(item.getString("utf-8"));
					}else if(fieldName.equals("ntitle")){
						news.setNtitle(item.getString("utf-8"));
					}else if(fieldName.equals("nauthor")){
						news.setNauthor(item.getString("utf-8"));
					}else if(fieldName.equals("nsummary")){
						news.setNsummary(item.getString("utf-8"));
					}else if(fieldName.equals("ncontent")){
						news.setNcontent(item.getString("utf-8"));
					}
					SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					news.setNcreatedate(format.format(new Date()));
					news.setNmodifydate(format.format(new Date()));
					flag=true;
				}else{  //如果是文件域
					String fileName=item.getName();
					//Arrays.asList用于将后面的一组字符串转换成一个list集合
					List<String> fileType = Arrays.asList("gif", "jpg", "jpeg");
					String ext=fileName.substring(fileName.lastIndexOf(".")+1);
					if(fileName!=null&&!fileName.equals("")&&!fileType.contains(ext)){
						flag=false;
		out.print("<script type='text/javascript'>alert('上传失败，文件类型只能是gif、jpg、jpeg');location.href='<%=basePath%>/newspages/news_add.jsp';</script>");
				
			
			/*	
				<script type="text/javascript">
					alert("上传失败，文件类型只能是gif、jpg、jpeg");
					location.href="<%=basePath%>/newspages/news_add.jsp";
				</script>*/
					
					}else if(fileName!=null&&!fileName.equals("")&&fileType.contains(ext)){
						File saveFile=new File(uploadPath,item.getName());
						try {
							item.write(saveFile);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						//记录上传的文件名
						uploadFileName=item.getName();
						//将上传的路径和文件名存进数据库中.
						news.setNpicpath(uploadPath+"\\"+uploadFileName);
						System.out.println("上传成功后的文件名为:" + uploadFileName);
						flag = true;
					}
				}
			}
		}
		if(flag){
			if(xg.equals("xiugai")){
	   			nb.updateNewsByNid(news,Integer.parseInt(nid));	
	   			request.getRequestDispatcher("../newspages/admin.jsp").forward(request, response);
	   		}else{
	   			int num=nb.saveNews(news);
		   		if(num>0){
		   			request.getRequestDispatcher("../newspages/admin.jsp").forward(request, response);
		   		}else{
		   			response.sendRedirect("../newspages/news_add.jsp");
		   		}
	   		}
		
		
		}
		
	}

}
